package com.ujiuye.servlet;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ser.Serializers;
import com.ujiuye.bean.User;
import com.ujiuye.service.Homework01Service;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * 姓名的非空、唯一验证
 * 手机号 非空、格式、唯一验证
 */


@WebServlet("/homework01Servlet")
public class Homework01Servlet  extends BaseServlet {

    private Homework01Service hs = new Homework01Service();
    /**
     * 验证账号唯一
     * @param req
     * @param resp
     */
    public void usernameIsUnique(HttpServletRequest req,HttpServletResponse resp) throws IOException {
        //接收账号
        String username = req.getParameter("username");
        int i = hs.usernameIsUnique(username);

        // i > 0 查得到 不让注册   = 0 查不到 让注册
        //true  绿色 让注册    false  红色 不让注册
        PrintWriter w = resp.getWriter();

        w.print(i == 0);

    }

    /**
     * 验证手机号
     * @param req
     * @param resp
     */
    public void phoneIsUnique(HttpServletRequest req,HttpServletResponse resp) throws IOException {
        String phone = req.getParameter("phone");
        int i = hs.phoneIsUnique(phone);
        resp.getWriter().print(i == 0);

    }

    /**
     * 模糊搜索
     * @param req
     * @param resp
     */
    public void dimQuery(HttpServletRequest req,HttpServletResponse resp) throws IOException {
        String username = req.getParameter("username");
        List<User> lists =  hs.dimQuery(username);
        //查询的list不为空 传递给前台

        //把list集合转成json
        String json = new ObjectMapper().writeValueAsString(lists);
        resp.getWriter().print(json);


    }
}
